package com.xh.easyretry.listener;

import com.xh.easyretry.common.Element;
import com.xh.easyretry.common.XHRetryContext;
import com.xh.easyretry.handler.ClassHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Slf4j
public abstract class RetryListener<T extends Element> {

    private final ClassHandler classHandler = ClassHandler.getInstance();

    public abstract void listen(T t);

    protected void doWithSpecifyMethod(XHRetryContext retryContext, String methodName) {
        if (!StringUtils.hasText(methodName)) {
            return;
        }
        try {
            Method method = retryContext.getMethod();
            Class<?> beanClass = retryContext.getBeanClass();
            Class<?>[] argTypes = method.getParameterTypes();
            Method specifyMethod = classHandler.getMethod(beanClass, methodName, argTypes);

            Object bean = retryContext.getBean();
            Object[] args = retryContext.getArgs();
            classHandler.processMethod(specifyMethod, bean, args);
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
